﻿using Nett;
using OfficeOpenXml;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace socket_client
{
    public partial class Form1 : Form
    {
        private string host;
        private int port;
        private string databasePath;
        private int startModel;
        private string dBPassword = "纛爨鬣鷆";
        private List<string> tableList = new List<string>();
        private string ExcelFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "SaveData");
        private Int16 hour;
        private Int16 minute;
        private int intervalMinutes;
        private bool runImmediatelyIfMissed;
        private TcpSocket tcpClient;
        private DatabaseManager dB;

        public Form1()
        {
            // 设置 EPPlus 非商业用途许可证（免费）
            ExcelPackage.LicenseContext = OfficeOpenXml.LicenseContext.NonCommercial;
            InitializeComponent();
            // 绑定日志输出的textBox
            AsyncFileLogger.Initialize(this.textBox1);
            // 读取配置文件
            readConfig();
            // 启用定时器
            startTimer();
        }

        void readConfig()
        {
            try
            {
                // 读取配置 
                var config = Toml.ReadFile<AppConfig>(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..", "..", "Config//Config.ini"));
                this.host = config.Server.Host;
                this.port = config.Server.Port;
                //this.dBPassword = config.DataBase.password;
                this.databasePath = config.DataBase.dbPath;
                this.tableList = config.DataBase.tableList;
                this.startModel = config.Scheduler.startModel;
                this.intervalMinutes = config.Scheduler.intervalMinutes;
                this.hour = (short)config.Scheduler.hour;
                this.minute = (short)config.Scheduler.minute;
                this.runImmediatelyIfMissed = config.Scheduler.runImmediatelyIfMissed;

                AsyncFileLogger.WriteLog(dBPassword);
                AsyncFileLogger.WriteLog($"==========={host}:{port}============");
            }
            catch (Exception ex)
            {
                AsyncFileLogger.WriteLog($"配置文件读取失败错误: {ex.Message}");
            }
        }
        private async void hostConnectButton_Click(object sender, EventArgs e)
        {
            try
            {
                // 添加目录创建异常处理
                if (!Directory.Exists(ExcelFolder))
                {
                    Directory.CreateDirectory(ExcelFolder);

                    AsyncFileLogger.WriteLog($"创建文件{ExcelFolder}");
                }
                dB = new DatabaseManager(databasePath, dBPassword);
                dB.GetConnection();
                tcpClient = new TcpSocket();

                foreach (var table in tableList)
                {
                    DataTable dataStudy = dB.GetTable($"SELECT * FROM {table}");
                    AsyncFileLogger.WriteLog($"{ExcelFolder}\\{table}.xlsx");
                    dB.saveExcel(dataStudy, table, ExcelFolder + $"\\{table}.xlsx");
                    await tcpClient.SendFileAsync(ExcelFolder + $"\\{table}.xlsx", host, port);
                }
            }
            catch (Exception ex)
            {
                AsyncFileLogger.WriteLog($"连接失败：{ex.Message}");
                hostConnectButton.Enabled = true;
            }

        }
        private void startTimer()
        {
            // 添加每日任务
            if (startModel == 0)
            {
                AsyncFileLogger.WriteLog("定时任务启动");
                GlobalScheduler.AddDailyTask(
                    taskId: "pullData",
                    action: () => sendExcelTask(),
                    // 每天9:30执行
                    targetTime: new TimeSpan(hour, minute, 0),
                    runImmediatelyIfMissed: runImmediatelyIfMissed
                );
            }
            // 添加间隔任务
            else if (startModel == 1)
            {
                GlobalScheduler.AddIntervalTask(
                taskId: "sync_cache",
                action: () => sendExcelTask(),
                intervalMinutes: intervalMinutes, // 每1分钟执行一次
                runImmediately: runImmediatelyIfMissed // 立即执行首次
                ); 
            }
        }
        private async Task sendExcelTask()
        {
            try
            {
                // 添加目录创建异常处理
                if (!Directory.Exists(ExcelFolder))
                {
                    Directory.CreateDirectory(ExcelFolder);

                    AsyncFileLogger.WriteLog($"创建文件{ExcelFolder}");
                }
                dB = new DatabaseManager(databasePath, dBPassword);
                dB.GetConnection();
                tcpClient = new TcpSocket();

                foreach (var table in tableList)
                {
                    DataTable dataTable = dB.GetTable($"SELECT * FROM {table}");
                    dB.saveExcel(dataTable, "Report", ExcelFolder + $"\\{table}.xlsx");
                    await tcpClient.SendFileAsync(ExcelFolder + $"\\{table}.xlsx", host, port);
                }
            }
            catch (Exception ex)
            {
                AsyncFileLogger.WriteLog($"连接失败：{ex.Message}");
                hostConnectButton.Enabled = true;
            }
        }
        private void databaseConnectButton_Click(object sender, EventArgs e)
        {

        }

        private void ipTextBox_TextChanged(object sender, EventArgs e)
        {
            host = ipTextBox.Text;
        }

        private void portTextBox_TextChanged(object sender, EventArgs e)
        {

        }

        private void databaseTextBox_TextChanged(object sender, EventArgs e)
        {
            databasePath = databaseTextBox.Text;
        }

        ~Form1()
        {
            // 应用退出时释放资源
            GlobalScheduler.Dispose();
        }
        public class ServerConfig
        {
            public string Host { get; set; }
            public int Port { get; set; }
        }
        public class DataBaseConfig
        {
            public string dbPath { get; set; }
            public string password { get; set; }
            public List<string> tableList { get; set; }
        }
        public class SchedulerConfig
        {
            public int startModel { get; set; }
            public int intervalMinutes { get; set; }
            public int hour { get; set; }
            public int minute { get; set; }
            public bool runImmediatelyIfMissed { get; set; }
        }
        public class AppConfig
        {
            public ServerConfig Server { get; set; }
            public DataBaseConfig DataBase { get; set; }
            public SchedulerConfig Scheduler { get; set; }
        }
    }
}
